<?php
/**
 * @author fld 2021-06-16
 * @desc 菜单业务类
 */
namespace App\Service\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class MenuService
{
    private $module_name = "菜单管理";
    /**
     * @author fld 2021-06-16
     * @desc 获取菜单数据列表
     * @return array
     */
    public function getRoleMenuList(){
        $admin = session('admin');
        $role_id = $admin['role_id'];
        if(Cache::has('menu_list_'.$role_id)){
            return Cache::get('menu_list_'.$role_id);
        }else{
            if($role_id == 1){//超级管理员所有菜单权限
                $field = ['id','menu_name','pid','route','icon'];
                $list = DB::table('menu')->where(['is_show'=>1,'pid'=>0])->orderBy('sortby','asc')->get($field);
                $list = objectToArray($list);
                $menu_list = [];
                foreach($list as $k=>$v){
                    $child_menu_list = $this->getChildMenuList($v['id'], $role_id);
                    $v['child'] = $child_menu_list;
                    $menu_list[] = $v;
                }
            }else{
                $field = ['m.id','m.menu_name','m.pid','m.route','m.icon'];
                $list = DB::table('menu as m')
                        ->leftJoin('role_menu as rm', 'm.id', '=', 'rm.menu_id')
                        ->where(['m.is_show'=>1,'m.pid'=>0,'rm.role_id'=>$role_id])
                        ->orderBy('m.sortby','asc')
                        ->get($field);
                $list = objectToArray($list);
                $menu_list = [];
                foreach($list as $k=>$v){
                    $child_menu_list = $this->getChildMenuList($v['id'],$role_id);
                    $v['child'] = $child_menu_list;
                    $menu_list[] = $v;
                }
            }
            Cache::put('menu_list_'.$role_id, $menu_list);
            return $menu_list;
        }
    }

    /**
     * @author fld 2016-06-16
     * @desc 获取子类菜单数据列表
     * @param $pid  父类id
     * @param $role_id  角色id
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getChildMenuList($pid, $role_id){
        $field = ['m.id','m.menu_name','m.pid','m.route','m.icon'];
        if($role_id == 1){
            $list = DB::table('menu as m')->where(['m.is_show'=>1,'m.pid'=>$pid])->orderBy('m.sortby','asc')->get($field);
        }else{
            $list = DB::table('menu as m')
                  ->leftJoin('role_menu as rm', 'm.id', '=', 'rm.menu_id')
                  ->where(['m.is_show'=>1,'m.pid'=>$pid,'rm.role_id'=>$role_id])
                  ->orderBy('m.sortby','asc')
                  ->get($field);
        }
        $list = objectToArray($list);
        return $list;
    }

    /**
     * @author fld 2021-06-17
     * @desc 获取所有的菜单数据
     * @return array|mixed
     */
    public function getAllMenuList(){
        if(Cache::has('all_menu_list')){
            return Cache::get('all_menu_list');
        }else{
            $field = ['id','menu_name','pid'];
            $list = DB::table('menu')->where(['pid'=>0])->orderBy('sortby','asc')->get($field);
            $list = objectToArray($list);
            $menu_list = [];
            foreach($list as $k=>$v){
                $child_menu_list = $this->getAllChildMenuList($v['id']);
                $v['child'] = $child_menu_list;
                $menu_list[] = $v;
            }
            Cache::put('all_menu_list', $menu_list);
            return $menu_list;
        }
    }

    /**
     * @author fld 2016-06-17
     * @desc 获取所有子类菜单数据列表
     * @param $pid
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getAllChildMenuList($pid){
        $field = ['id','menu_name','pid','route','icon'];
        $list = DB::table('menu')->where(['pid'=>$pid])->orderBy('sortby','asc')->get($field);
        $list = objectToArray($list);
        $menu_list = [];
        foreach($list as $k=>$v){
            $child_menu_list = $this->getAllChildMenuList($v['id']);
            $v['child'] = $child_menu_list;
            $menu_list[] = $v;
        }
        return $menu_list;
    }

    /**
     * @author fld 2021-06-21
     * @desc 获取所有菜单数据列表
     * @return array
     */
    public function getMenuList(){
        $field = ['id','menu_name','pid', 'route', 'is_show', 'sortby'];
        $list = DB::table('menu')->orderBy('sortby','asc')->get($field);
        $list = objectToArray($list);
        return $list;
    }

    /**
     * @author fld 2021-06-21
     * @desc   根据条件获取菜单信息
     * @param $condition
     * @return mixed
     */
    public function getMenuByCondition($condition){
        $menu = DB::table('menu')->where($condition)->first();
        return objectToArray($menu);
    }

    /**
     * @author fld 2021-06-21
     * @desc 通过id获取菜单信息
     * @param $id
     * @return mixed
     */
    public function getMenuById($id){
        $menu = DB::table('menu')->where('id',$id)->first();
        return objectToArray($menu);
    }

    /**
     * @author fld 2021-06-21
     * @desc 新增菜单
     * @param $data
     * @return int
     */
    public function addMenu($data){
        return DB::table('menu')->insertGetId($data);
    }

    /**
     * @author fld 2021-06-21
     * @desc 更新菜单
     * @param $id
     * @param $data
     * @return int
     */
    public function updateMenuById($id, $data){
        return DB::table('menu')->where('id',$id)->update($data);
    }

    /**
     * @author fld 2021-06-21
     * @desc 新增或更新菜单信息
     * @return array
     */
    public function addOrUpdateMenu(){
        $params = request()->all();
        if(empty($params['menu_name'])){
            return ['code' => 1,'message' => '菜单名称不能为空'];
        }
        if(empty($params['id'])) {
            $menu_info = $this->getMenuByCondition(['menu_name' => trim($params['menu_name'])]);
        }else{
            $condition = [];
            $condition[] = ['menu_name','=',trim($params['menu_name'])];
            $condition[] = ['id','!=',$params['id']];
            $menu_info = $this->getMenuByCondition($condition);
        }
        if (!empty($menu_info)) {
            return ['code' => 1, 'message' => '菜单名称已存在'];
        }
        DB::beginTransaction();
        $insert_data = [];
        $insert_data['menu_name'] = trim($params['menu_name']);
        $insert_data['pid'] = $params['pid'];
        $insert_data['icon'] = trim($params['icon']);
        $insert_data['route'] = trim($params['route']);
        $insert_data['is_show'] = empty($params['is_show']) ? 0 : $params['is_show'];
        $insert_data['sortby'] = empty($params['sortby']) ? 20 : $params['sortby'];
        if(!empty($params['id'])){
            $insert_data['create_time'] = time();
            $res = $this->updateMenuById($params['id'], $insert_data);
            if($res !== false){
                addActionLog(['module_name'=>$this->module_name,'type'=>'edit','log_remark'=>'修改编号:'.$params['id'].',菜单名称:'.trim($params['menu_name']).'菜单信息']);
            }
        }else{
            $insert_data['create_time'] = time();
            $res = $this->addMenu($insert_data);
            if($res !== false){
                addActionLog(['module_name'=>$this->module_name,'type'=>'add','log_remark'=>'新增编号:'.$res.',菜单名称:'.trim($params['menu_name']).'菜单信息']);
            }
        }
        if($res !== false){
            $this->flushRoleMenu(0);
            DB::commit();
            return ['code' => 0,'message' => '保存菜单成功'];
        }else{
            DB::rollBack();
            return ['code' => 1,'message' => '保存菜单失败'];
        }
    }

    /**
     * @author fld 2021-06-21
     * @desc 删除菜单信息
     * @param $id
     * @return array
     */
    public function deleteMenuById($id){
        if($id == 1){
            return ['code' => 1,'message' => '无法删除该菜单'];
        }
        $menus = $this->getMenuById($id);
        $res = DB::table('menu')->where('id', $id)->delete();
        if($res !== false){
            $this->flushRoleMenu(0);
            addActionLog(['module_name'=>$this->module_name,'type'=>'delete','log_remark'=>'删除编号:'.$id.',菜单名称:'.$menus['menu_name'].'菜单信息']);
            return ['code' => 0,'message' => '删除菜单成功'];
        }else{
            return ['code' => 1,'message' => '删除菜单失败'];
        }
    }
    /**
     * @author fld 2021-06-21
     * @desc 删除菜单信息
     * @param $id
     * @return array
     */
    public function update_status(){
        $params = request()->all();
        $id = $params['id'];
        $state = $params['state'];
        if(empty($id) || strlen($state) < 1){
            return ['code' => 1,'message' => '参数不存在'];
        }
        $menus = $this->getMenuById($id);
        $res = DB::table('menu')->where('id', $id)->update(['is_show'=>$state]);
        if($res !== false){
            $this->flushRoleMenu(0);
            addActionLog(['module_name'=>$this->module_name,'type'=>'edit','log_remark'=>'修改编号:'.$id.',菜单名称:'.$menus['menu_name'].'显示状态']);
            return ['code' => 0,'message' => '修改菜单成功'];
        }else{
            return ['code' => 1,'message' => '修改菜单失败'];
        }
    }


    /**
     * @author fld 2021-06-21
     * @desc 清除权限菜单缓存
     */
    public function flushRoleMenu($role_id){
        Cache::forget('all_menu_list');
        if($role_id == 0){
            $roleService = new RoleService();
            $role_list = $roleService->getRoleList();
            foreach($role_list as $k=>$v){
                Cache::forget('menu_list_'.$v['id']);
            }
        }else{
            Cache::forget('menu_list_'.$role_id);
        }
    }

    /**
     * @author fld 2021-06-21
     * @desc 设置角色权限信息（用来判断角色权限）
     * @param $role_id
     */
    public function setRoleMenuAction($role_id){
        $field = ['m.id','m.menu_name','m.pid','m.route','m.icon'];
        $list = DB::table('menu as m')
            ->leftJoin('role_menu as rm', 'm.id', '=', 'rm.menu_id')
            ->where(['rm.role_id'=>$role_id])
            ->orderBy('m.sortby','asc')
            ->get($field);
        $list = objectToArray($list);
        $role_menu_action = [];
        foreach($list as $k=>$v){
            $route = $v['route'];
            if(!empty($route)){
                $route_array = explode('/',$route);
                if(count($route_array) == 3){
                    array_push($role_menu_action, $route_array[2].'_');
                }else{
                    array_push($role_menu_action, $route_array[2].'_'.$route_array[3]);
                }
            }
        }
        $role_menu_action = array_unique($role_menu_action);
        session(['role_menu_action'=>$role_menu_action]);
        return $role_menu_action;
    }

    /**
     * @author fld 2021-06-21
     * @desc 设置角色权限信息（用来判断角色权限）
     * @param $role_id
     */
    public function setSuperRoleMenuAction(){
        $list = $this->getMenuList();
        $list = objectToArray($list);
        $role_menu_action = [];
        foreach($list as $k=>$v){
            $route = $v['route'];
            if(!empty($route)){
                $route_array = explode('/',$route);
                if(count($route_array) == 3){
                    array_push($role_menu_action, $route_array[2].'_');
                }else{
                    array_push($role_menu_action, $route_array[2].'_'.$route_array[3]);
                }
            }
        }
        $role_menu_action = array_unique($role_menu_action);
        session(['role_menu_action'=>$role_menu_action]);
        return $role_menu_action;
    }

}